#!/usr/bin/env python
#coding=utf-8

#******************************************
#This file for XCMD, created by OpenThings.
#Using this to automate the test procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-13.
#******************************************

print("  ==================================================")
print("  *   Welcome to xGateway-using MQTT and TCP!     *")
print("  *      Smart Control with XCONSOLE .             *")
print("  *     By openthings@163.com. 2014-12.            *")
print("  *------------------------------------------------*")
print("  *    基于消息总线的网关，扩展远程控制到互联网。   *")
print("  ==================================================")

import sys
import datetime
import socket, sys
import paho.mqtt.client as mqtt

#======================================================        
#Using Mosquitto MQTT Borker.
#Local Server.
Broker = "localhost"
PORT = 1883
CHANNEL = "/inode/info"

#Lan Server.
#Broker = "192.168.105.8"
#Broker = "112.124.67.178"
#Broker = "m2m.eclipse.org"

#======================================================
def on_connect(mqttc, obj, rc):
    print "Connected=>>MQTT://",Broker,":",PORT,CHANNEL

def on_publish(mqttc, obj, mid):
    print("OnPublish, mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
    print("Log:"+string)

def on_message(mqttc, obj, msg):
    curtime = datetime.datetime.now()
    strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
    print(strcurtime + ": " + msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    on_exec(str(msg.payload))

def on_exec(strcmd):
    print "Exec:",strcmd
    strExec = strcmd
    
#============================================
if __name__ == "__main__":
	mqttc = mqtt.Client()
	mqttc.on_message = on_message
	mqttc.on_connect = on_connect
	mqttc.on_publish = on_publish
	mqttc.on_subscribe = on_subscribe
	#mqttc.on_log = on_log

	mqttc.connect(Broker, PORT, 60)
	mqttc.subscribe(CHANNEL, 0)
	mqttc.loop_forever()
  
